package com.dc.project.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dc.common.annotation.DataScope;
import com.dc.common.constant.CustomConstants;
import com.dc.common.constant.CustomSqlConstants;
import com.dc.common.core.LoginUser;
import com.dc.common.exception.ServiceException;
import com.dc.common.utils.*;
import com.dc.common.vo.ResultVo;
import com.dc.project.system.dao.SysUserDao;
import com.dc.project.system.dto.SysUserDto;
import com.dc.project.system.entity.SysPost;
import com.dc.project.system.entity.SysRole;
import com.dc.project.system.entity.SysUser;
import com.dc.project.system.service.SysRoleMenuService;
import com.dc.project.system.service.SysUserPostService;
import com.dc.project.system.service.SysUserRoleService;
import com.dc.project.system.service.SysUserService;
import com.dc.project.system.vo.SysUserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * 系统用户表(SysUser)表服务实现类
 *
 * @author zhuangcy
 * @since 2021-06-01 14:30:43
 */
@Service("sysUserService")
public class SysUserServiceImpl extends ServiceImpl<SysUserDao, SysUser> implements SysUserService {
    @Autowired
    private SysUserPostService sysUserPostService;
    @Autowired
    private SysUserRoleService sysUserRoleService;
    @Autowired
    private SysRoleMenuService sysRoleMenuService;

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return
     */
    @Override
    public ResultVo queryById(Serializable id) {
        return ResultVo.success().data(this.getById(id));
    }

    /**
     * 分页查询系统用户表
     *
     * @param dto
     * @return
     */
    @DataScope
    @Override
    public ResultVo queryByPage(SysUserDto dto) {
        LoginUser userInfo = ShiroUtil.getUserInfo();
        IPage page = PageUtil.convert2PageParam(dto);
        dto.setAdminArray(CustomConstants.SUPER_ADMIN);
        dto.setUserId(userInfo.getUserId());
        IPage<SysUserVo> pageList = baseMapper.queryByPage(page, dto);
        return ResultVo.success().data(PageUtil.convert2PageResult(pageList));
    }

    /**
     * 新增系统用户表
     *
     * @param dto
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public ResultVo add(SysUserDto dto) {
        LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysUser::getAccount, dto.getAccount())
                .or().eq(SysUser::getUserCode, dto.getUserCode())
                .last(CustomSqlConstants.LIMIT_1);
        SysUser one = this.getOne(queryWrapper);
        if (null != one || isUserContains(dto)) {
            throw new ServiceException("登录账号或工号已存在");
        }
        if (StringUtil.isNotEmpty(dto.getPassword())) {
            dto.setPassword(RsaUtil.encrypt(dto.getPassword()));
        } else {
            dto.setPassword(RsaUtil.encrypt(CustomConstants.DEFAULT_PASSWORD));
        }
        SysUser sysUser = new SysUser();
        BeanUtil.copyBeanProp(sysUser, dto);
        if (this.save(sysUser)) {
            sysUserPostService.addUserPosts(sysUser.getUserId(), dto.getPostIds());
            sysUserRoleService.addUserRoles(sysUser.getUserId(), dto.getRoleIds());
            return ResultVo.success();
        }
        throw new ServiceException();
    }

    private boolean isUserContains(SysUserDto dto) {
        return Arrays.asList(CustomConstants.SUPER_ADMIN).contains(dto.getAccount());
    }

    /**
     * 编辑系统用户表
     *
     * @param dto
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public ResultVo edit(SysUserDto dto) {
        LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysUser::getAccount, dto.getAccount())
                .or().eq(SysUser::getUserCode, dto.getUserCode())
                .last(CustomSqlConstants.LIMIT_1);
        SysUser one = this.getOne(queryWrapper);
        boolean exist = null != one && !one.getUserId().equals(dto.getUserId());
        if (exist || isUserContains(dto)) {
            throw new ServiceException("登录账号或工号已存在");
        }
        SysUser sysUser = new SysUser();
        BeanUtil.copyBeanProp(sysUser, dto);
        if (this.updateById(sysUser)) {
            sysUserPostService.addUserPosts(sysUser.getUserId(), dto.getPostIds());
            sysUserRoleService.addUserRoles(sysUser.getUserId(), dto.getRoleIds());
            return ResultVo.success();
        }
        throw new ServiceException();
    }

    /**
     * 根据主键删除系统用户表
     *
     * @param id 主键
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public ResultVo delete(Serializable id) {
        return ResultVo.verify(this.removeById(id));
    }

    /**
     * 根据主键重置系统用户密码
     *
     * @param userId
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public ResultVo resetPwd(Integer userId) {
        SysUser sysUser = new SysUser();
        sysUser.setUserId(userId);
        sysUser.setPassword(RsaUtil.encrypt(CustomConstants.DEFAULT_PASSWORD));
        if (this.updateById(sysUser)) {
            return ResultVo.success().msg("已重置该用户密码为初始默认密码");
        }
        return ResultVo.failed();
    }

    /**
     * 变更系统用户密码
     *
     * @param userId
     * @param oldPwd
     * @param newPwd
     * @param checkPwd
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public ResultVo changePwd(Integer userId, String oldPwd, String newPwd, String checkPwd) {
        SysUser user = this.getById(userId);
        if (null == user) {
            return ResultVo.failed().msg("用户不存在");
        }
        if (!RsaUtil.decrypt(user.getPassword()).equals(newPwd)) {
            return ResultVo.failed().msg("原始密码不正确");
        }
        if (newPwd.equals(checkPwd)) {
            return ResultVo.failed().msg("新密码与确认密码不一致");
        }
        SysUser sysUser = new SysUser();
        sysUser.setPassword(RsaUtil.encrypt(newPwd));
        sysUser.setUserId(userId);
        if (this.updateById(sysUser)) {
            return ResultVo.success().msg("修改成功，请重新登录");
        }
        return ResultVo.failed();
    }

    /**
     * 根据登录账号查询用户信息
     *
     * @param username
     * @return
     */
    @Override
    public SysUser getUserByAccount(String username) {
        LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysUser::getAccount, username);
        return this.getOne(queryWrapper);
    }

    /**
     * 根据用户ID查询角色权限相关信息
     *
     * @param userId
     * @return
     */
    @Override
    public List<SysRole> getUserRoleByUserId(Integer userId) {
        return sysUserRoleService.getUserRoles(userId);
    }

    /**
     * 根据角色id 查询权限
     *
     * @param roleIds
     * @return
     */
    @Override
    public Set<String> getMenuIdByRoleIds(Set<Integer> roleIds) {
        if (roleIds.isEmpty()) {
            return new HashSet<>();
        }
        return sysRoleMenuService.getMenuIdByRoleIds(roleIds);
    }

    /**
     * 根据用户ID查询岗位信息
     *
     * @param userId
     * @return
     */
    @Override
    public List<SysPost> getUserPosts(Integer userId) {
        return sysUserPostService.getUserPostsByUserId(userId);
    }

}